package hedron.db.model;

import hedron.Application;
import hedron.db.DBManager;
import java.sql.Connection;
import java.sql.ResultSet;

public class Stock extends AbstractModel {

	private long STOCK_ID = 0;
	public String STOCK_NAME = EMPTY_STR;
	public String STOCK_CODE = EMPTY_STR;

	public long GROUP_ID = 0;
	public String GROUP_NAME = EMPTY_STR;
	public long QTY = 0;

	@Override
	public long getID() {
		return STOCK_ID;
	}

	@Override
	public String getIDName() {
		return "STOCK_ID";
	}

	@Override
	public String getTableName() {
		return "HSTOCK";
	}

	public Stock() {}

	public Stock(ResultSet rs) {
		if (rs == null) {
			throw new IllegalArgumentException("ResultSet might not be null");
		}
		if (!load(rs)) {
			throw new IllegalArgumentException("cannot load from ResultSet");
		}
	}

	@Override
	public boolean load(ResultSet rs) {
		DBManager db = Application.DB;
		STOCK_ID = db.getLong(rs, getIDName(), 0);
		if (STOCK_ID == 0) {
			return false;
		}
		STOCK_NAME = db.getString(rs, "STOCK_NAME");
		STOCK_CODE = db.getString(rs, "STOCK_CODE");
		GROUP_ID = db.getLong(rs, "GROUP_ID");
		GROUP_NAME = db.getString(rs, "GROUP_NAME");
		QTY = db.getLong(rs, "QTY");
		return true;
	}

	@Override
	public boolean isValid() {
		return isNotEmpty(STOCK_NAME);
	}

	@Override
	public boolean store(Connection conn) {
		StringBuilder sql = new StringBuilder();
		StringBuilder searchtext = new StringBuilder();
		{// build search index
			searchtext.append(GROUP_NAME).append(' ');
			searchtext.append(STOCK_NAME).append(' ');
			searchtext.append(STOCK_CODE);
		}
		if (getID() <= 0) {// insert
			STOCK_ID = Application.ID.getNewID();
			sql.append("insert into ");
			sql.append(getTableName());
			sql.append("(STOCK_ID,GROUP_ID,STOCK_CODE,STOCK_NAME,SEARCHTEXT) values(?,?,?,?,?)");
			return db.ddlQuery(conn, sql.toString(), STOCK_ID, GROUP_ID, STOCK_CODE, STOCK_NAME, searchtext.toString());
		} else {// update
			sql.append("update ");
			sql.append(getTableName());
			sql.append(" SET GROUP_ID = ?, STOCK_CODE = ?, STOCK_NAME = ?, SEARCHTEXT = ?");
			sql.append(" where STOCK_ID = ").append(STOCK_ID);
			return db.ddlQuery(conn, sql.toString(), GROUP_ID, STOCK_CODE, STOCK_NAME, searchtext.toString());
		}
	}

	@Override
	public boolean delete(Connection conn) {
		return false;
	}

}
